<template>
  <card-group-solt
    @handleClick="changeTab"
    :activeName="activeName"
    :tabPanes="tabPanes"
    class="card-ques"
    :cardLoading="loading">
    <template :slot="'search'">
      <search :type="activeName">
        <template :slot="'subMenu'">
          <el-tabs v-model.trim="subMenu" class="questionSubTab" @tab-click="changeSubTab">
            <el-tab-pane :label="subTabPane.name" :name="subTabPane.type" v-for="(subTabPane, index) in subTabPanes" :key="subTabPane.type + index"></el-tab-pane>
          </el-tabs>
        </template>
        <template :slot="'select'">
          <v-select
            :selectOptions="search.quickSelect"
            :isQuesTitle="subMenu === 'complete' ? $t('questionnaire.quesCompleteTime') : $t('questionnaire.quesCreatTime')"
            :form="search[activeName][subMenu]"
            @quickSelect="quickSelect"></v-select>
        </template>
        <template :slot="'inputSearch'">
          <input-search @quickSearch="nomalSearch"
                        :placeHolder="search.placeHolder"
                        :form="search[activeName].isChildren.nomalForm">
          </input-search>
        </template>
        <template :slot="'advancedSearch'">
          <advanced-search v-if="search[activeName].isChildren.adv"
            :adv="search[activeName].isChildren.adv"
            :badge="search[activeName].isChildren.adv.badgeList"
            :activeName="activeName"
            :formItemsConfig="formItemsConfigs[activeName]"
            @selectChange="selectChange"
            @advSearch="advSearch"
            @getBatchNoByTime="getBatchNoByTime"
            @confirmNewItemsConfig="handleConfirmNewItemsConfig"
          >

          </advanced-search>
        </template>
        <template :slot="'refresh'">
          <refresh v-if="search[activeName].isChildren.refresh" @refresh="handleRefresh" :class="'positionClass'"></refresh>
        </template>
        <template :slot="'advSchBadge'">
          <advSchBadge v-if="search[activeName].isChildren.adv.badgeList"
                       :badge="search[activeName].isChildren.adv.badgeList"
                       @removeBadge="removeBadge"></advSchBadge>
        </template>
        <template v-if="search[activeName].isChildren.selfExport" :slot="'export'">
          <export v-if="authority.export && search[activeName].isChildren.selfExport" @export="exportQues" fontSize="18"></export>
        </template>
        <template v-if="search[activeName].isChildren.delete" :slot="'delete'">
          <delete v-if="authority.delete && search[activeName].isChildren.delete && !$store.state.session.user.isAdmin" @delete="deleteQues" :fontSize="'18'"></delete>
        </template>
        <template v-if="search[activeName].isChildren.assign" :slot="'assign'">
          <assign v-if="authority.assign && search[activeName].isChildren.assign && !$store.state.session.user.isAdmin" @assign="assignBtn" :fontSize="'18'"></assign>
        </template>
      </search>
      <assign-questionnaire
      :isAssignDialog="isAssignDialog"
      :count="totalAssignCount"
      @assignSubmit="assignSave">
      </assign-questionnaire>
    </template>
    <template :slot="'pagination'">
      <pagination
        :customerShow="true"
        :small="search[activeName].pagination.small"
        :currentPage="search[activeName].pagination.currentPage"
        :count="count"
        :allCount="allCount"
        :moreFlag="moreFlag"
        :type="type"
        :tabType="activeName"
        @turnPage="turnPage"
        @getAllCount="getAllCount"
        :totalPage="totalPage">
      </pagination>
    </template>
    <template :slot="'cardList'">
      <question-card
        :cardList="cardList"
        :count="count"
        :type="type"
        :tabType="activeName"
        :condition = "search[activeName].isChildren.adv.form"
        @changeCardItem="changeCardItem"
        >
      </question-card>
    </template>
  </card-group-solt>
</template>
<script>
  import bus from 'src/store/eventBus'
  //  import CardGroupSolt from '@/components/public-modules/card'
  //  import Search from '@/components/public-modules/card/search'
  import CardGroupSolt from '@/components/public-modules/card/NewIndex.vue'
  import Search from '@/components/public-modules/card/search/NewIndex'
  import Select from '@/components/public-modules/card/search/Select'
  import QuestionCard from './QuestionCard'
  import InputSearch from '@/components/public-modules/card/search/InputSearch'
  import AdvancedSearch from '@/components/public-modules/card/search/Advanced1Search'
  import Pagination from '@/components/public-modules/card/Pagination'
  import Refresh from '../../ui-modules/icon/Refresh'
  import AdvSchBadge from '@/components/public-modules/card/search/AdvSchBadge'
  import Export from '../../ui-modules/icon/Export'
  import Delete from '../../ui-modules/icon/Delete'
  import Assign from '../../ui-modules/icon/Assign'
  import AssignQuestionnaire from './AssignQuestionnaire'
  import { addZhuGeTrack } from '@/utils/addZhuGeTrack.js'
  import {deepClone, getDateTime, trimObjEmptyValue, getFormatDateTime, searchDataReturn} from '@/utils/m7Utils'
  import { MessageBox, Message } from 'element-ui'
  export default {
    name: 'QuestionCardGroup',
    data () {
      return {
        allCount: 0,
        moreFlag: false,
        loading: true,
        isAssignDialog: false,
        totalAssignCount: 0,
        PAGE_SIZE: 10,
        pages: 0,
        activeName: this.$route.params.tabType || 'questionnaire_my',
        type: 'questionnaire',
        dialogVisible: false,
        subMenu: 'all',
        tabPanes: [
          {name: this.$t('questionnaire.myQuestionnaire'), type: 'questionnaire_my'},
          {name: this.$t('questionnaire.allQuestionnaire'), type: 'questionnaire_all'}
        ],
        subTabPanes: [
          {name: this.$t('public.all'), type: 'all'},
          {name: this.$t('questionnaire.unComplete'), type: 'uncomplete'},
          {name: this.$t('questionnaire.unConfirm'), type: 'unconfirm'},
          {name: this.$t('questionnaire.complete'), type: 'complete'}
        ],
        search: {
          isAdvSearch: false,
          isSearch: false, // 是否正在执行搜索
          advSearchCondition: {}, // 高级搜索的查询条件展示
          quickSelect: [
            {label: this.$t('questionnaire.ques_all'), value: 'quickSearch_all'},
            {label: this.$t('questionnaire.ques_today'), value: 'quickSearch_0'},
            {label: this.$t('questionnaire.ques_yesterday'), value: 'quickSearch_1'},
            {label: this.$t('questionnaire.ques_oneWeek'), value: 'quickSearch_7'},
            {label: this.$t('questionnaire.ques_oneMounth'), value: 'quickSearch_30'}
          ],
          placeHolder: this.$t('questionnaire.phonePlaceHolding'),
          questionnaire_all: {
            all: { value: 'quickSearch_7' },
            uncomplete: { value: 'quickSearch_7' },
            unconfirm: { value: 'quickSearch_7' },
            complete: { value: 'quickSearch_7' },
            searchCard: 'buSearchCard',
            show: true,
            pagination: {
              small: true,
              currentPage: 1
            },
            isChildren: {
              rel: false,
              refresh: true,
              select: [],
              nomal: true,
              selfExport: false,
              delete: false,
              assign: false,
              nomalForm: {phone: '', query: ''},
              adv: {
                form: {name: null, ownercom: null, owner: null, ownerdep: null, phone: null, createTime: null, lastUpdateTime: [], assignStatus: null, temp_id: null, result: null, batchNo: null, batchRemark: null},
                advSearchOptions: {
                  localed: [
                    {label: this.$t('questionnaire.name'), name: 'name', inputType: 'input'},
                    {label: this.$t('questionnaire.phone'), name: 'phone', inputType: 'input'},
                    {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time'},
                    {label: this.$t('questionnaire.lastUpdateTime'), name: 'lastUpdateTime', inputType: 'time'},
                    {label: this.$t('questionnaire.assignStatus'), name: 'assignStatus', inputType: 'select', data: [{label: this.$t('public.pleasePick'), value: ''}, {label: '未分配', value: 'unassigned__未分配'}, {label: '已分配', value: 'assigned__已分配'}]},
                    {label: this.$t('questionnaire.owner'), name: 'owner', inputType: 'owner'},
                    {label: this.$t('questionnaire.tempId'), name: 'temp_id', inputType: 'select', data: []},
                    {label: this.$t('questionnaire.result'), name: 'result', inputType: 'select', data: []},
                    {label: this.$t('questionnaire.batchNo'), name: 'batchNo', inputType: 'select', multiple: true, filterable: true, allowCreate: true, remoteMethod: 'getBatchNoByTime', data: []},
                    {label: this.$t('questionnaire.batchRemark'), name: 'batchRemark', inputType: 'input', multiple: true, filterable: true, allowCreate: true, remoteMethod: 'getBatchRemarkByTime', data: []}
                  ],
                  custom: [
                  ]
                },
                badgeList: {}
              }
            }
          },
          questionnaire_my: {
            all: { value: 'quickSearch_7' },
            uncomplete: { value: 'quickSearch_7' },
            unconfirm: { value: 'quickSearch_7' },
            complete: { value: 'quickSearch_7' },
            searchCard: 'bmSearchCard',
            show: true,
            pagination: {
              small: true,
              currentPage: 1
            },
            isChildren: {
              rel: false,
              refresh: true,
              nomal: true,
              selfExport: false,
              delete: false,
              assign: false,
              nomalForm: {phone: '', query: ''},
              adv: {
                form: {name: null, phone: null, createTime: null, lastUpdateTime: [], temp_id: null, result: null, batchNo: null, batchRemark: null},
                advSearchOptions: {
                  localed: [
                    {label: this.$t('questionnaire.name'), name: 'name', inputType: 'input'},
                    {label: this.$t('questionnaire.phone'), name: 'phone', inputType: 'input'},
                    {label: this.$t('public.createTime'), name: 'createTime', inputType: 'time'},
                    {label: this.$t('questionnaire.lastUpdateTime'), name: 'lastUpdateTime', inputType: 'time'},
                    {label: this.$t('questionnaire.tempId'), name: 'temp_id', inputType: 'select', data: []},
                    {label: this.$t('questionnaire.result'), name: 'result', inputType: 'select', data: []},
                    {label: this.$t('questionnaire.batchNo'), name: 'batchNo', inputType: 'select', data: [], multiple: true, filterable: true, allowCreate: true, remoteMethod: 'getBatchNoByTime'},
                    {label: this.$t('questionnaire.batchRemark'), name: 'batchRemark', inputType: 'input', data: [], multiple: true, filterable: true, allowCreate: true, remoteMethod: 'getBatchRemarkByTime'}
                  ],
                  custom: [
                  ]
                },
                badgeList: {}
              }
            }
          }
        },
        qu: {},
        formItemsConfigs: {}
      }
    },
    provide () {   //  高级搜索  设置  创建时间项 为disabled  checked
      return {
        itemsDisabled: {
          questionnaire_my: {
            createTime: true
          },
          questionnaire_all: {
            createTime: true
          }
        }
      }
    },
    beforeMount () {
      // 设置高级搜索默认时间
      let week = searchDataReturn('week')   //   近一周
      this.search.questionnaire_all.isChildren.adv.form.createTime = [new Date(week.createTime$begin), new Date(week.createTime$end)]
      this.search.questionnaire_my.isChildren.adv.form.createTime = [new Date(week.createTime$begin), new Date(week.createTime$end)]
      this.allCount = 0
      this.loading = true
      let searchData = {
        querydata: {
          page: 1,
          morePage: 1
        },
        queryType: this.activeName
      }
      searchData.querydata = this.renderQuickSearchData(searchData.querydata)
      this.search[this.activeName].isChildren.refresh = true
      this.search[this.activeName].isChildren.selfExport = false
      this.search[this.activeName].isChildren.delete = this.activeName !== 'questionnaire_my'
      this.search[this.activeName].isChildren.assign = false
      getQuesTmpls(this.$store).then(() => {
        this.tabPanes.forEach((tabPane) => {
          this.search[tabPane.type].isChildren.adv.advSearchOptions.localed.forEach((item) => {
            if (item.name === 'temp_id') {
              item.data = this.quesTmpls
            }
          })
        })
        //  getQuestionList(this.$store, searchData).then(() => {
        //    this.loading = false
        //  })
        this.$store.dispatch('quesList', searchData).then(() => {
          if (searchData.querydata.page === 1) {
            this.pages = this.count / this.PAGE_SIZE
          }
          let _qu = deepClone(searchData)
          _qu.queryCount = true
          this.qu = _qu
          this.loading = false
        })
      })

      // 高级搜索自定义布局配置
      this.$store.dispatch('getAdvSearchConfig', {
        searchType: 'QuestionCardGroup'
      }).then((config) => {
        this.formItemsConfigs = config || {}
      })
    },
    watch: {
      'refreshLeftCard': 'refreshLeft'
    },
    computed: {
      cardList () {
        console.log(this.$store.state[this.type][this.type + 'List'])
        if (this.$store.state[this.type][this.type + 'List'].more) {
          this.moreFlag = true
        } else {
          this.moreFlag = false
        }
        return this.$store.state[this.type][this.type + 'List'].list
      },
      refreshLeftCard () {
        return this.$store.state.questionnaire.refreshLeft
      },
      count () {
        console.log(this.$store.state[this.type][this.type + 'List'])
        if (this.$store.state[this.type][this.type + 'List'].more) {
          this.moreFlag = true
        } else {
          this.moreFlag = false
        }
        return this.$store.state[this.type][this.type + 'List'].count
      },
      totalPage () {
        return Math.ceil(this.$store.state[this.type][this.type + 'List'].count / this.PAGE_SIZE) || 0
      },
      quesTmpls () {
        let tmpls = []
        let quesTmpls = this.$getCache('questionnaireTemp')
        if (quesTmpls) {
          quesTmpls.forEach(ele => {
            tmpls.push({label: ele.name, value: ele._id + '__' + ele.name})
          })
        }
        return tmpls
      },
      authority () {
        let result = {delete: false, assign: false, export: false}
        let auths = this.$store.state.session.user.funcIds
        if (auths && auths.indexOf('func_questionnaire_delete') !== -1) {
          result.delete = true
        }
        if (auths && auths.indexOf('func_questionnaire_assign') !== -1) {
          result.assign = true
        }
        if (auths && auths.indexOf('func_questionnaire_export') !== -1) {
          result.export = true
        }
        return result
      }
    },
    methods: {
      getAllCount () {
        console.log(this.$store.state[this.type][this.type + 'List'])
        this.allCount = 0
        let form = this.qu
        console.log(form, 'form')
        form.searchAllCount = true // 此参数是防止vuex的值被改动
        this.$store.dispatch('quesListCount', form).then((res) => {
          this.allCount = res.count
          let more = false
          this.moreFlag = false
          this.$store.commit('ques/QUES_LIST_MORE', {more})
        })
      },
      changeCardItem () {
        this.$emit('changeCardItem')
      },
      clearSearchQuery () {
        this.search.isAdvSearch = false
        let currentTab = this.search[this.activeName]
        currentTab.pagination.currentPage = 1
        for (let key in currentTab.isChildren.adv.form) {
          if (key !== 'custom') {
            if (key === 'batchNo') {
              currentTab.isChildren.adv.form[key] = []
            } else {
              currentTab.isChildren.adv.form[key] = null
            }
          } else {
            currentTab.isChildren.adv.form[key] = {}
          }
        }
        for (let key in this.search[this.activeName].isChildren.nomalForm) {
          this.search[this.activeName].isChildren.nomalForm[key] = null
        }
        let items = this.search[this.activeName].isChildren.adv.advSearchOptions.localed
        for (let i = 0; i < items.length; i++) {
          if (items[i].name === 'batchNo') {
            items[i].data = []
          }
        }
        this.search[this.activeName].isChildren.adv.badgeList = null
        // 设置高级搜索默认时间
        let week = searchDataReturn('week')   //   近一周
        this.search.questionnaire_all.isChildren.adv.form.createTime = [new Date(week.createTime$begin), new Date(week.createTime$end)]
        this.search.questionnaire_my.isChildren.adv.form.createTime = [new Date(week.createTime$begin), new Date(week.createTime$end)]
      },
      changeTab (tabName) {
        addZhuGeTrack(tabName)
        this.pages = 0
        this.allCount = 0
        this.activeName = tabName
        let self = this
        self.loading = true
        this.search[this.activeName].isChildren.refresh = true
        if (this.subMenu === 'unconfirm' || this.subMenu === 'uncomplete') {
          this.search[this.activeName].isChildren.assign = this.activeName !== 'questionnaire_my'
        }

        if (this.subMenu === 'complete') {
          this.search[this.activeName].isChildren.selfExport = true
          this.search[this.activeName].isChildren.assign = false
        } else if (this.subMenu === 'all') {
          this.search[this.activeName].isChildren.assign = false
        } else {
          this.search[this.activeName].isChildren.selfExport = false
        }

        this.search[this.activeName].isChildren.delete = this.activeName !== 'questionnaire_my'
        // 清空搜索中的查询条件
        this.clearSearchQuery()
        let queryData = {
          querydata: {
            page: 1,
            morePage: 1,
            limit: this.PAGE_SIZE
          },
          queryType: this.activeName
        }
        queryData.querydata = this.renderQuickSearchData(queryData.querydata)
        let queryType = getCurrentQueryType(this.subMenu, this.activeName)
        queryData.queryType = queryType
        this.$router.push({ path: '/index/questionnaire' })
//        getQuestionList(this.$store, queryData).then(() => {
//          this.loading = false
//        })
        this.$store.dispatch('quesList', queryData).then(() => {
          if (queryData.querydata.page === 1) {
            this.pages = this.count / this.PAGE_SIZE
          }
          let _qu = deepClone(queryData)
          _qu.queryCount = true
          this.qu = _qu
          this.loading = false
        })
      },
      changeSubTab (tab) {
        this.pages = 0
        this.allCount = 0
        let subTabName = tab.name
        this.subMenu = subTabName
        this.loading = true
        if (subTabName === 'all') {
          this.search[this.activeName].isChildren.refresh = true
          this.search[this.activeName].isChildren.selfExport = false
          this.search[this.activeName].isChildren.delete = this.activeName !== 'questionnaire_my'
          this.search[this.activeName].isChildren.assign = false
        } else if (subTabName === 'uncomplete') {
          this.search[this.activeName].isChildren.refresh = true
          this.search[this.activeName].isChildren.selfExport = false
          this.search[this.activeName].isChildren.delete = this.activeName !== 'questionnaire_my'
          this.search[this.activeName].isChildren.assign = this.activeName !== 'questionnaire_my'
        } else if (subTabName === 'unconfirm') {
          this.search[this.activeName].isChildren.refresh = true
          this.search[this.activeName].isChildren.selfExport = false
          this.search[this.activeName].isChildren.delete = this.activeName !== 'questionnaire_my'
          this.search[this.activeName].isChildren.assign = this.activeName !== 'questionnaire_my'
        } else if (subTabName === 'complete') {
          this.search[this.activeName].isChildren.refresh = true
          this.search[this.activeName].isChildren.selfExport = true
          this.search[this.activeName].isChildren.delete = this.activeName !== 'questionnaire_my'
          this.search[this.activeName].isChildren.assign = false
        }

        // 清空搜索中的查询条件
        this.clearSearchQuery()
        let queryData = {
          querydata: {
            page: 1,
            morePage: 1,
            limit: this.PAGE_SIZE
          }
        }
        queryData.querydata = this.renderQuickSearchData(queryData.querydata)
        let queryType = getCurrentQueryType(subTabName, this.activeName)
        queryData.queryType = queryType
//        let that = this
//        getQuestionList(this.$store, queryData).then(() => {
//          that.loading = false
//        })
        this.$store.commit('ques/QUES_TYPE', subTabName)

        this.$router.push({ path: '/index/questionnaire' })
        this.$store.dispatch('quesList', queryData).then(() => {
          if (queryData.querydata.page === 1) {
            this.pages = this.count / this.PAGE_SIZE
          }
          let _qu = deepClone(queryData)
          _qu.queryCount = true
          this.qu = _qu
          this.loading = false
        })
      },
      exportQues () {
        if (!this.search[this.activeName].isChildren.adv.form.temp_id) {
          this.$message.error(this.$t('questionnaire.noTempId'))
          return false
        }
        this.$store.dispatch('quesListCount', this.qu).then((res) => {
          if (res.success) {
            if (res.count > 100000) {
              this.$message.error(this.$t('questionnaire.exportMore100000Msg'))
              return
            }
            let querydata = {}
            let form = this.search[this.activeName].isChildren.adv.form
            querydata = processAdvQuery(querydata, form, {})
            querydata.status = 'complete'
            if (querydata.createTime_begin_date) {
              querydata.createTime = {}
              querydata.createTime['$gte'] = querydata.createTime_begin_date
              querydata.createTime_begin_date = ''
            }
            if (querydata.createTime_end_date) {
              if (!querydata.createTime) querydata.createTime = {}
              querydata.createTime['$lte'] = querydata.createTime_end_date
              querydata.createTime_end_date = ''
            }

            if (querydata.lastUpdateTime_begin_date) {
              querydata.lastUpdateTime = {}
              querydata.lastUpdateTime['$gte'] = querydata.lastUpdateTime_begin_date
              querydata.lastUpdateTime_begin_date = ''
            }
            if (querydata.lastUpdateTime_end_date) {
              if (!querydata.lastUpdateTime) querydata.lastUpdateTime = {}
              querydata.lastUpdateTime['$lte'] = querydata.lastUpdateTime_end_date
              querydata.lastUpdateTime_end_date = ''
            }

            if (this.activeName === 'questionnaire_my') {
              querydata.owner = this.$store.state.session.user._id
            }
            trimObjEmptyValue(querydata)
            this.$store.dispatch('exportQues', querydata)
          }
        })
      },
      deleteQues () {
        let form = this.search[this.activeName].isChildren.adv.form
        let queryData = {}
        if (this.search.isAdvSearch) {
          queryData = processAdvQuery(queryData, form, {})
        } else {
          queryData = deepClone(this.search[this.activeName].isChildren.nomalForm)
        }
        if (this.subMenu === 'unconfirm') {
          queryData.status = 'confirm'
        } else if (this.subMenu === 'all') {
          queryData.status = null
        } else {
          queryData.status = this.subMenu
        }
        queryData = this.renderQuickSearchData(queryData)
        this.$store.dispatch('getQuesCount', queryData).then((response) => {
          MessageBox.confirm(this.$t('questionnaire.deleteQuesMessageWithLength', {length: response.count}), this.$t('questionnaire.deleteQuesConfirm'), {
            confirmButtonText: this.$t('public.confirm'),
            cancelButtonText: this.$t('public.cancel'),
            cancelButtonClass: 'primary_btn',
            confirmButtonClass: 'primary_btn',
            type: 'warning'
          }).then((v) => {
            this.$store.dispatch('deleteQues', queryData).then(() => {
              Message.success({
                message: this.$t('questionnaire.deleteQuesSuccess')
              })
              this.handleRefresh() // 刷新列表
              this.$router.push({ path: '/index/questionnaire' })
            })
          }).catch((err) => {
            if (err === 'cancel') {}
          })
        })
      },
      quickSelect (value) {
        let form = this.search[this.activeName].isChildren.adv.form
        let morePage = 1
        this.pages = 0
        this.search[this.activeName].pagination.currentPage = 1
        if (this.search.isAdvSearch) {
          this.search.isAdvSearch = false
          // 清空高级搜索选项
          for (let key in form) {
            if (key === 'custom') {
              form.custom = {}
            } else {
              if (key === 'batchNo') {
                form[key] = []
              } else {
                form[key] = null
              }
            }
          }
          let items = this.search[this.activeName].isChildren.adv.advSearchOptions.localed
          for (let i = 0; i < items.length; i++) {
            if (items[i].name === 'batchNo') {
              items[i].data = []
            }
          }
        }
        this.nomalSearch(null, 1, morePage)
      },
      assignBtn () {
        this.$store.dispatch('quesListCount', this.qu).then((res) => {
          if (res.success) {
            this.isAssignDialog = true
            this.totalAssignCount = res.count
          } else {
            this.isAssignDialog = true
            this.totalAssignCount = 0
          }
        })
      },
      /**
       * @param assignCount 指的是输入框里填入的数值
       * @param owners 指的是所有座席的值集合
       */
      assignSave (query) {
        if (query.type === 'cancel') {
          this.isAssignDialog = false
          return
        }
        let owners = query.owners
        let assignCount = query.assignCount
        this.$store.dispatch('quesListCount', this.qu).then((res) => {
          if (res.success) {
            let totalCount = res.count
            if (assignCount > totalCount) {
              this.$message({message: this.$t('questionnaire.assignFailTips2', {num: totalCount}), type: 'error'})
              return
            }
            let assignTotalNum = 0
            owners.forEach((owner) => {
              let num = owner.count
              if (num && parseInt(num) > 0) {
                assignTotalNum += parseInt(num, 10)
              }
            })
            if (assignTotalNum > assignCount) {
              this.$message({message: this.$t('questionnaire.assignFailTips2', {num: assignCount}), type: 'error'})
              return
            }
            let form = this.search[this.activeName].isChildren.adv.form
            let queryData = {}
            if (this.search.isAdvSearch) {
              queryData = processAdvQuery(queryData, form, {})
            } else {
              queryData = this.search[this.activeName].isChildren.nomalForm
              queryData = this.renderQuickSearchData(queryData)
            }
            queryData.status = this.subMenu === 'unconfirm' ? 'confirm' : this.subMenu
            let data = {owners: owners, total: totalCount, query: queryData}
            this.$store.dispatch('saveQuesAssign', data).then((res) => {
              if (res.success) {
                this.isAssignDialog = false
                this.handleRefresh()
              }
            })
          }
        })
      },
//      changeButtonShow (newValue) {
//        console.log(newValue)
//        this.search[this.activeName].isChildren.refresh = true
//        this.search[this.activeName].isChildren.selfExport = false
//        this.search[this.activeName].isChildren.delete = newValue !== 'questionnaire_my'
//        this.search[this.activeName].isChildren.assign = false
//      },
      selectChange (selectObj) {
        let selectName = selectObj.selectName
        let selectValue = selectObj.selectValue
        // 问卷模板类型改变
        if (selectName === 'temp_id') {
          let tmplId = selectValue ? selectValue.substr(0, selectValue.indexOf('__')) : ''
          getQuesTmplResults(this.$store, tmplId).then((tmpl) => {
            if (!tmpl) {
              return
            }
            let qstatus = tmpl.qstatus || {success: this.$t('questionnaire.successStatus'), invalid: this.$t('questionnaire.invalidStatus'), noAnswer: this.$t('questionnaire.noAnswerStatus'), imparity: this.$t('questionnaire.imparityStatus'), other: this.$t('questionnaire.otherStatus')}
            let qstatusSelectData = []
            for (let key in qstatus) {
              let item = {label: qstatus[key], value: key + '__' + qstatus[key]}
              qstatusSelectData.push(item)
            }
            this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
              if (item.name === 'result') {
                this.search[this.activeName].isChildren.adv.form.result = null
                item.data = qstatusSelectData
              }
            })
          })
        } else if (selectName === 'ownercom' || selectName === 'owner' || selectName === 'ownerdep') {
          this.search[this.activeName].isChildren.adv.form.ownercom = null
          this.search[this.activeName].isChildren.adv.form.owner = null
          this.search[this.activeName].isChildren.adv.form.ownerdep = null
          this.search[this.activeName].isChildren.adv.form[selectName] = selectValue
        }
      },
      getBatchNoByTime () {
        let searchQuery = {}
        let form = this.search[this.activeName].isChildren.adv.form
        if (form.createTime && form.createTime.length > 0 && form.createTime[0] !== null) {
          searchQuery.start = getDateTime(form.createTime[0])
        }
        if (form.createTime && form.createTime.length > 1 && form.createTime[1] !== null) {
          searchQuery.end = getDateTime(form.createTime[1])
        }
        this.$store.dispatch('getBatchNoByTime', searchQuery).then(res => {
          this.search[this.activeName].isChildren.adv.advSearchOptions.localed.forEach((item) => {
            if (item.name === 'batchNo') {
              item.data = res.data.map(obj => ({label: obj.batchNo, value: obj.batchNo}))
            }
          })
        })
      },
      nomalSearch (value, pageNum, morePage) {
        this.allCount = 0
        this.search.isSearch = true
        let self = this
        self.loading = true

        this.search[this.activeName].isChildren.adv.badgeList = {} // 清除高级搜索项
        this.search.isAdvSearch = false

        this.search[self.activeName].isChildren.nomalForm.phone = value
        let querydata = this.renderQuickSearchData(deepClone(this.search[self.activeName].isChildren.nomalForm))
        delete querydata.query
        querydata.page = pageNum || 1
        querydata.morePage = morePage || 1
        self.search[self.activeName].pagination.currentPage = pageNum || 1
        let queryType = getCurrentQueryType(this.subMenu, this.activeName)
//        getQuestionList(this.$store, {querydata, queryType}).then(() => {
//          self.loading = false
//          self.search[self.activeName].pagination.currentPage = pageNum || 1
//        })

        this.$store.dispatch('quesList', {querydata, queryType}).then(() => {
          if (querydata.page === 1) {
            this.pages = this.count / this.PAGE_SIZE
          }
          let _qu = deepClone({querydata, queryType})
          _qu.queryCount = true
          this.qu = _qu
//          self.search[self.activeName].pagination.currentPage = 1
          this.loading = false
        })
      },
      renderQuickSearchData (searchData) {
        let self = this
        let quickSearchDate = this.search[self.activeName][self.subMenu].value
        var searchStatus = quickSearchDate.split('_')[1] // 快捷搜索的时间范围
        var lastDate = getFormatDateTime(new Date()).substring(0, 19)
        var beginDate = ''
        if (searchStatus !== 'all') {
          if (searchStatus === '0') {
            beginDate = getFormatDateTime(new Date()).substring(0, 10) + ' 00:00'
          } else if (searchStatus === '1') {
            beginDate = getFormatDateTime(new Date(new Date() - 24 * 60 * 60 * 1000)).substring(0, 10) + ' 00:00'
            lastDate = getFormatDateTime(new Date(new Date() - 24 * 60 * 60 * 1000)).substring(0, 10) + ' 23:59'
          } else {
            beginDate = getFormatDateTime(new Date(new Date() - searchStatus * 24 * 60 * 60 * 1000)).substring(0, 16)
          }
        }
        if (!this.search.isAdvSearch) {
          if (this.subMenu === 'complete' && searchStatus !== 'all') {
            searchData.lastUpdateTime_begin_date = beginDate
            searchData.lastUpdateTime_end_date = lastDate
          } else if (searchStatus && searchStatus !== 'all') {
            searchData.createTime_begin_date = beginDate
            searchData.createTime_end_date = lastDate
          }
        }
        return searchData
      },
      refreshLeft () {
        if (this.$store.state.questionnaire.refreshLeft !== '') {
          this.handleRefresh()
        }
      },
      handleRefresh () {
        this.allCount = 0
        this.search[this.activeName].pagination.currentPage = 1
        if (this.search.isAdvSearch) {
          this.advSearch()
        } else {
          this.nomalSearch(this.search[this.activeName].isChildren.nomalForm.query)
        }
      },
      removeBadge () {
        this.resetAdvSearch()
        this.search[this.activeName][this.subMenu].value = 'quickSearch_7'
        this.quickSelect()
        this.createTimeInit()
      },
      resetAdvSearch () {
        let form = this.search[this.activeName].isChildren.adv.form
        for (let key in form) {
          if (key === 'custom') {
            form.custom = {}
          } else {
            if (key === 'batchNo') {
              form[key] = []
            } else {
              form[key] = null
            }
          }
        }
      },
      advSearch (clearBadge, pageNum, morePage) {
        this.allCount = 0
        this.search.isSearch = true
        let self = this
        self.loading = true
        let form = this.search[this.activeName].isChildren.adv.form
        let tempArr = {}
        let searchQuery = {}
        if (clearBadge === true) {
          self.search.isAdvSearch = false
          // 清空高级搜索选项
          for (let key in form) {
            if (key === 'custom') {
              form.custom = {}
            } else {
              if (key === 'batchNo') {
                form[key] = []
              } else {
                form[key] = null
              }
            }
          }
          let items = this.search[this.activeName].isChildren.adv.advSearchOptions.localed
          for (let i = 0; i < items.length; i++) {
            if (items[i].name === 'batchNo') {
              items[i].data = []
            }
          }
          searchQuery = {}
        } else {
          self.search.isAdvSearch = true
          searchQuery = processAdvQuery(searchQuery, form, tempArr)
          // 去除普通搜索的条件
          for (let key in this.search[this.activeName].isChildren.nomalForm) {
            this.search[this.activeName].isChildren.nomalForm[key] = null
          }
          // 去除快捷搜索
          self.search[self.activeName][self.subMenu].value = 'quickSearch_all'
        }
        this.search[this.activeName].isChildren.adv.badgeList = tempArr
        searchQuery.page = pageNum || 1
        self.search[self.activeName].pagination.currentPage = pageNum || 1
        let queryType = getCurrentQueryType(this.subMenu, this.activeName)
//        this.search[self.activeName].pagination.currentPage = 1
//        getQuestionList(this.$store, {querydata: searchQuery, queryType: queryType}).then(() => {
//          self.loading = false
//        })
        if (clearBadge) { // 如果关闭高级搜索 则启用快捷搜索选项
          searchQuery = this.renderQuickSearchData(searchQuery)
        }
        searchQuery.morePage = morePage || 1
        this.$store.dispatch('quesList', {querydata: searchQuery, queryType: queryType}).then(() => {
          if (searchQuery.page === 1) {
            this.pages = this.count / this.PAGE_SIZE
          }
          let _qu = deepClone({querydata: searchQuery, queryType: queryType})
          _qu.queryCount = true
          this.qu = _qu
          this.loading = false
        })
      },
      turnPage (pageNum) {
        this.allCount = 0
        if (this.search.isSearch && pageNum < 2) {
          this.search.isSearch = false
          return
        }
        let morePage = 1
        if (pageNum >= this.pages && pageNum % this.pages === 0) {
          morePage = pageNum / this.pages + 1
        } else if (this.pages) {
          morePage = Math.floor(pageNum / this.pages + 1)
        }
        this.search[this.activeName].pagination.currentPage = pageNum
        if (this.search.isAdvSearch) {
          this.advSearch(false, pageNum, morePage)
        } else {
          this.nomalSearch(this.search[this.activeName].isChildren.nomalForm.query, pageNum, morePage)
        }
        // 一定要设置为false,这样才代表是翻页,而不是搜索
        this.search.isSearch = false
      },
      // 创建时间初始化
      createTimeInit () {
        let week = searchDataReturn('week')
        this.search.questionnaire_my.isChildren.adv.form.createTime = [new Date(week.createTime$begin), new Date(week.createTime$end)]
        this.search.questionnaire_all.isChildren.adv.form.createTime = [new Date(week.createTime$begin), new Date(week.createTime$end)]
      },
      handleConfirmNewItemsConfig ({data: formItemsConfig, done}) {
        var formItemsConfigs = deepClone(this.formItemsConfigs)
        formItemsConfigs[this.activeName] = formItemsConfig

        this.$store.dispatch('saveAdvSearchConfig', {
          searchType: 'QuestionCardGroup',
          config: formItemsConfigs
        }).then(() => {
          this.formItemsConfigs = formItemsConfigs
          done()
        })
      }
    },
    components: {
      QuestionCard,
      CardGroupSolt,
      InputSearch,
      AdvancedSearch,
      Pagination,
      Refresh,
      Search,
      AdvSchBadge,
      Delete,
      Export,
      Assign,
      AssignQuestionnaire,
      'v-delete': Delete,
      'v-select': Select
    },
    mounted () {
      bus.$on('refreshQuestionnaireLeftCardList', () => {
        this.handleRefresh()
      })
    },
    beforeDestroy () {
      bus.$off('refreshQuestionnaireLeftCardList')
    }
  }

  function getQuesTmpls (store) {
    return store.dispatch('getQuesTmpls')
  }

  function getQuesTmplResults (store, value) {
    return store.dispatch('getCache', {type: 'questionnaireTemp', id: value})
  }
  // 获取问卷卡片数据
//  function getQuestionList (store, searchData) {
//    return store.dispatch('quesList', searchData)
//  }
  function getCurrentQueryType (subTab, activeName) {
    let queryType = ''
    switch (subTab) {
      case 'all':
        if (activeName === 'questionnaire_my') {
          queryType = 'questionnaire_my'
        } else {
          queryType = 'questionnaire_all'
        }
        break
      case 'uncomplete':
        if (activeName === 'questionnaire_my') {
          queryType = 'my_questionnaire_uncomplete'
        } else {
          queryType = 'questionnaire_uncomplete'
        }
        break
      case 'unconfirm':
        if (activeName === 'questionnaire_my') {
          queryType = 'my_questionnaire_unconfirm'
        } else {
          queryType = 'questionnaire_unconfirm'
        }
        break
      case 'complete':
        if (activeName === 'questionnaire_my') {
          queryType = 'my_questionnaire_complete'
        } else {
          queryType = 'questionnaire_complete'
        }
        break
      default :
        queryType = 'questionnaire_my'
        break
    }
    return queryType
  }
  function processAdvQuery (searchQuery, form, tempArr) {
    searchQuery = deepClone(form)
    let custom = searchQuery.custom
    // deepClone后createtiem里日期消失
    if (form.createTime && form.createTime.length > 0 && form.createTime[0] !== null) {
      searchQuery.createTime_begin_date = getDateTime(form.createTime[0])
    }
    if (form.createTime && form.createTime.length > 1 && form.createTime[1] !== null) {
      searchQuery.createTime_end_date = getDateTime(form.createTime[1])
    }
    if (form.lastUpdateTime && form.lastUpdateTime.length > 0 && form.lastUpdateTime[0] !== null) {
      searchQuery.lastUpdateTime_begin_date = getDateTime(form.lastUpdateTime[0])
    }
    if (form.lastUpdateTime && form.lastUpdateTime.length > 1 && form.lastUpdateTime[1] !== null) {
      searchQuery.lastUpdateTime_end_date = getDateTime(form.lastUpdateTime[1])
    }
    let batchNo = searchQuery.batchNo
    let batchNos = ''
    if (batchNo) {
      batchNo.forEach(one => {
        batchNos += one + ';'
      })
    }
    delete searchQuery.createTime
    delete searchQuery.lastUpdateTime
    searchQuery.batchNo = batchNos
    for (let key in searchQuery) { // 搜索条件
      if (searchQuery[key] && key !== 'custom') {
        tempArr[key] = searchQuery[key]
        if (key === 'temp_id' || key === 'result' || key === 'assignStatus' || key === 'owner' || key === 'ownercom' || key === 'ownerdep') {
          tempArr[key] = searchQuery[key].substr(searchQuery[key].indexOf('__') + 2)
          searchQuery[key] = searchQuery[key].substr(0, searchQuery[key].indexOf('__'))
        }
      }
    }
    for (let i in custom) {
      searchQuery[i] = custom[i]
    }
    delete searchQuery.custom
    return searchQuery
  }
</script>
<style lang="stylus" scoped>
  @import "../../../assets/common.styl"
  .questionSubTab
    background-color $c-back
</style>
